import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

// 采购单仓库：主表 + 明细（本地存储实现）
export const usePurchaseStore = defineStore('purchase', () => {
  const STORAGE_KEY = 'erppos_purchases'
  const bills = ref([])

  const persist = () => localStorage.setItem(STORAGE_KEY, JSON.stringify(bills.value))

  const initialize = () => {
    const cached = localStorage.getItem(STORAGE_KEY)
    if (cached) {
      bills.value = JSON.parse(cached)
      return
    }
    bills.value = []
    persist()
  }

  const todayStr = () => new Date().toISOString().slice(0,10)

  const genSn = () => {
    const date = todayStr().replace(/-/g, '')
    const seq = String(Date.now()).slice(-6)
    return `PO${date}${seq}`
  }

  // 创建采购单（主表 + 明细）
  const createBill = ({ supplierId, supplierName, billDate, items, remark = '', operator = '系统' }) => {
    const now = new Date().toISOString()
    const totalQty = items.reduce((s, it) => s + Number(it.qty || 0), 0)
    const totalAmount = items.reduce((s, it) => s + Number(it.qty || 0) * Number(it.price || 0), 0)
    const bill = {
      id: 'B' + Date.now(),
      sn: genSn(),
      supplierId: supplierId || '',
      supplierName: supplierName || '',
      billDate: billDate || todayStr(),
      status: '已保存',
      totalQty: Number(totalQty),
      totalAmount: Number(totalAmount.toFixed(2)),
      remark,
      operator,
      createdAt: now,
      items: (items || []).map((x, idx) => ({
        lineNo: idx + 1,
        code: x.code || '',
        name: x.name || '',
        styleNo: x.styleNo || '',
        color: x.color || '',
        size: x.size || '',
        qty: Number(x.qty || 0),
        price: Number(x.price || 0),
      })),
    }
    bills.value.unshift(bill)
    persist()
    return bill
  }

  // 简单过滤（按供应商/单号/日期）
  const filtered = (filters = {}) => {
    const s = (filters.search || '').toLowerCase()
    const [start, end] = filters.range || []
    return bills.value.filter(b => {
      if (s && !(b.sn || '').toLowerCase().includes(s) && !(b.supplierName || '').toLowerCase().includes(s)) return false
      if (start || end) {
        const d = (b.billDate || '').slice(0,10)
        if (start && d < start) return false
        if (end && d > end) return false
      }
      return true
    })
  }

  const exportBills = (list = null) => {
    const exportList = list || bills.value
    const headers = ['单号','日期','供应商','总数量','总金额','状态','创建时间']
    const rows = exportList.map(b => [b.sn, b.billDate, b.supplierName, b.totalQty, b.totalAmount, b.status, b.createdAt])
    const csv = [headers.join(','), ...rows.map(r => r.join(','))].join('\n')
    const blob = new Blob(['\ufeff' + csv], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = `采购单_${todayStr()}.csv`
    link.click()
  }

  const totalBills = computed(() => bills.value.length)

  return {
    bills,
    initialize,
    genSn,
    createBill,
    filtered,
    exportBills,
    totalBills,
  }
})


